﻿using ConfExpert.Datasets;
using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevTeam;

using System;
using System.Data;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo
{
    public partial class ParcaCikisEmri : XForm
    {
        bool KDept = false;
        MyData.xSepetLinesDataTable sel = new MyData.xSepetLinesDataTable();
        MyData.xSepetDataTable se = new MyData.xSepetDataTable();

        public ParcaCikisEmri()
        {
            InitializeComponent();
        }

        public ParcaCikisEmri(MyData.xSepetLinesDataTable _selectedRolls, MyData.xSepetDataTable _selectedArts, bool _KDept)
            : this()
        {
            KDept = _KDept;
            sel = _selectedRolls;
            se = _selectedArts;

        }

        private void KucukParcaTalebi_Load(object sender, EventArgs e)
        {
            gle.Properties.Assign(RI(Rp.Atelye));


            //gleCikisTipi.Properties.Assign(RI(Rp.HareketTipi));


            DataTable dt = AppSession.Lookups.HareketTipi.Select("HareketTipiId in (22,23,24,25,26,27,28)").CopyToDataTable();
            RepositoryItemGridLookUpEdit riCikisTipi = GetCustomGLE(dt, "Name", "HareketTipiId");
            gleCikisTipi.Properties.Assign(riCikisTipi);
            gleCikisTipi.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;
            cmbYontem.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;
            gleKime.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;

            gleCikisTipi.Closed += new ClosedEventHandler(gleCikisTipi_Closed);
            gleCikisTipi.EditValue = 22;

            gleKime.Properties.Assign(RI(Rp.V_User));
            gle.Properties.Assign(RI(Rp.V_Customer));

            gle.EditValueChanged += new EventHandler(gle_EditValueChanged);
            gle.EditValue = 1;
            gle.Properties.ReadOnly = true;

            this.Shown += new EventHandler(CikisEmri_Shown);

            btnOk.Click+=new EventHandler(btnOk_Click);
            btnCancel.Click+=new EventHandler(btnCancel_Click);
        }

        void gleCikisTipi_Closed(object sender, ClosedEventArgs e)
        {
            if (intParse(gleCikisTipi.EditValue) != 24)
            {
                gle.EditValue = 1;
                gle.Properties.ReadOnly = true;
            }
            else
                gle.Properties.ReadOnly = false;
        }

        void gle_EditValueChanged(object sender, EventArgs e)
        {
            labelControl3.Visible = gleKime.Visible = intParse(gle.EditValue) == 1;
        }


        void CikisEmri_Shown(object sender, EventArgs e)
        {
            gleKime.Focus();
            gleKime.EditValue = WhoAmI;
        }



        private void btnOk_Click(object sender, EventArgs e)
        {
            if (chkA4.Checked == false)
            {

                if (decimalParse(txtMetraj.EditValue) == 0 || decimalParse(txtMetraj.EditValue) > 5)
                {
                    ShowInfoMessage("Top bazında girilecek metraj değeri 0-5 mt. arası olmalıdır.");
                    return;
                }


                switch (cmbYontem.SelectedIndex)
                {
                    case 0: //Her artikelinden birer top
                        for (int i = sel.Rows.Count - 1; i >= 0; i--)
                            sel[i].QtySelected = txtMetraj.EditValue.ToDecimal();
                        break;

                    default:    //Tümü
                        foreach (MyData.xSepetRow r in se)
                        {
                            int ProductId = r.ProductId;
                            DataRow[] drs = sel.Select("ProductId=" + ProductId.ToString() + " AND Qty>=" + txtMetraj.EditValue.ToString().Replace(",", "."), "Qty");
                            if (drs.Length > 0)
                            {
                                int keep = intParse(drs[0]["RollId"]);

                                for (int i = sel.Rows.Count - 1; i >= 0; i--)
                                    if (sel[i].RollId == keep)
                                        sel[i].QtySelected = (decimal)txtMetraj.EditValue;
                                    else
                                        if (sel[i].ProductId == ProductId)
                                            sel.RemovexSepetLinesRow(sel[i]);

                            }
                        }
                        break;
                }


                string msg = "";
                foreach (MyData.xSepetLinesRow r in sel.Select("Qty<" + txtMetraj.EditValue.ToDecimal().ToString().Replace(",", "."), "Qty"))
                    msg += r.RollId + Environment.NewLine;

                if (!string.IsNullOrEmpty(msg))
                {
                    ShowInfoMessage("Aşağıda Id'si verilen topların metrajı, kesmek istediğiniz miktardan küçüktür!\r\n\r\n" + msg);
                    return;
                }

            }

            string xmlSel = sel.SerializeChanges();
            string xmlSe = se.SerializeChanges();
            object customerId = gle.EditValue;
            ds.xBuffer.Clear();

            bool authorized = true;
            if (!KDept)
            {
                GetDetails("xBuffer", "TransferKontrol2",
                xmlSel,
                xmlSe,
                null,   //OrderRef
                0,  //Brand
                0,  //Sezon
                WhoAmI,
                0,
                'P',
                string.Empty
                );


                if (ds.xBuffer.Rows.Count > 0)
                {
                    string str = string.Empty;
                    switch (ds.xBuffer[0].strVal)
                    {
                        case "YetkisizDepodan":
                            foreach (MyData.xBufferRow r in ds.xBuffer)
                                str += r.intVal.ToString() + Environment.NewLine;
                            XtraMessageBox.Show("Aşağıdaki topları önce kendi deponuza transfer etmelisiniz:\n\n" + str, "İşlem başarısız");
                            authorized = false;
                            break;

                    }
                    return;

                }
            }


            if (authorized)
            {
                var cikisEmriId = ExecuteScalar("InsParcaCikisEmri",
                    xmlSel,
                    xmlSe,
                    customerId, intParse(gleKime.EditValue),
                    decimalParse(txtMetraj.EditValue),
                    chkA4.Checked,
                    WhoAmI,
                    intParse(gleCikisTipi.EditValue), txtNot.Text);
                XtraMessageBox.Show(string.Format("{0} numaralı Parça Çıkış Emri başarıyla oluşturulmuştur.", cikisEmriId), "Parça Çıkış Emri");
                string command = string.Format("SHOW ConfExpert.Forms.Depo.Cikis.ParcaCikisEmirleri {0}", cikisEmriId);
                Mail.Send("riza.demir@karbel.com", "PARÇA Çıkış Talebi", string.Format("{0} Id'li parça çıkış talebi oluşturuldu.", cikisEmriId), "", command);
                this.DialogResult = DialogResult.OK;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void chkA4_CheckedChanged(object sender, EventArgs e)
        {
            if (chkA4.Checked)
            {
                txtMetraj.Enabled = false;
                txtMetraj.Text = "";
            }
            else
                txtMetraj.Enabled = true;
        }


    }
}
